<?php

namespace app\admin\controller\friend;

use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\chat\Message;
use think\Db;

/**
 * 联系人置顶管理
 *
 * @icon fa fa-circle-o
 */
class Friend extends Backend
{

    /**
     * Friend模型对象
     * @var \app\common\model\friend\Friend
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\friend\Friend;
        $this->view->assign("isDelList", $this->model->getIsDelList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $use_id = $this->request->request('use_id');
            $friendId = $this->getFriend($use_id);
            $map = !empty($use_id) ? ['friend_id' => ['in', $friendId]] : [];

            $list = $this->model->with(['user', 'to'])
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {
                $row->getRelation('user')->visible(['nickname']);
                $row->getRelation('to')->visible(['nickname']);
                if ($row->create_user == $use_id) {
                    $row->nickname = Db::name('user')->where('id',$row['friend_user_id'])->value('nickname');
                }else{
                    $row->nickname = Db::name('user')->where('id',$row['create_user'])->value('nickname');
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 关系树
     * @param $use_id
     * @return array
     * @author yuncran@126.com
     */
    public function getFriend($use_id)
    {
        $idArr = $this->model->where('relation', 'like', "%{$use_id},%")->column('friend_id');
        $userIdArr1 = $this->model->whereIn('friend_id', $idArr)->column('create_user');
        $userIdArr2 = $this->model->whereIn('friend_id', $idArr)->column('friend_user_id');
        $arr = array_unique(array_merge($userIdArr1, $userIdArr2));
        $responseArr = array_diff($arr, [$use_id]);
        $friendIdArr1 = $this->model->whereIn('create_user', $responseArr)->where('friend_user_id', $use_id)->column('friend_id');
        $friendIdArr2 = $this->model->whereIn('friend_user_id', $responseArr)->where('create_user', $use_id)->column('friend_id');
        $friendId = array_unique(array_merge($friendIdArr1, $friendIdArr2));
        return empty($friendId) ? [] : $friendId;
    }

    /**
     * 获取聊天记录
     * @return void
     * @author yuncran@126.com
     */
    public function get_chat($ids = null)
    {
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $friend_id = $this->request->request('friend_id');
        $user_id = $this->request->request('user_id');

        $friend = $this->model->where('friend_id', $friend_id)->field(['friend_id', 'create_user', 'friend_user_id'])->find();
        $param = ['from_user' => $friend['create_user'], 'to_user' => $friend['friend_user_id'],];
        // 查询最近的联系人
        $list = Message::field('*')
            ->where(function ($query) use ($param) {
                $query->where(['from_user' => $param['from_user']])->where(['to_user' => $param['to_user']]);
            })
            ->whereOr(function ($query) use ($param) {
                $query->where(['to_user' => $param['from_user']])->where(['from_user' => $param['to_user']]);
            })
            ->order(['msg_id' => 'ASC'])->select();
        $http = 'http://';
        $domain = $http . $_SERVER['HTTP_HOST'];
        foreach ($list as &$row) {

            $user = Db::name('user')->where('id', $row->from_user)->field('id,nickname,avatar')->find();
            $to_user = Db::name('user')->where('id', $row->to_user)->field('id,nickname,avatar')->find();

            $row->user_avatar = $domain . $user['avatar'];
            $row->to_user_avatar = $domain . $to_user['avatar'];

            $row->user_image = $domain . $row['content'];
            $row->user_video = $domain . $row['content'];
            $row->user = $user;
            $row->to_user = $to_user;

            $row->user_nickname = $user['nickname'];
            $row->to_user_nickname = $to_user['nickname'];
        }
        unset($row);
//        $result = array("total" => $list->total(), "rows" => $list->items());

        $this->assign('list', $list);
        $this->assign('id', $user_id);
        return $this->view->fetch();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");

        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            \app\common\model\chat\Message::where('friend_id','in', $ids)->delete();
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    
}
